#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define increment_used_memory(__n) do { \
    size_t _n = (__n); \
	if (emalloc_thread_safe) { \
		pthread_mutex_lock(&used_memory_mutex); \
		used_memory += _n; \
		pthread_mutex_unlock(&used_memory_mutex); \
	} else { \
		used_memory += _n; \
	} \
} while(0)

#define decrement_used_memory(__n) do { \
	size_t _n = (__n); \
	if (emalloc_thread_safe) { \
		pthread_mutex_lock(&used_memory_mutex); \
		used_memory -= _n; \
		pthread_mutex_unlock(&used_memory_mutex); \
	} else { \
		used_memory -= _n; \
	} \
} while(0)

static size_t used_memory = 0;
static int emalloc_thread_safe = 0;
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;

static void emalloc_oom(size_t size) {
	fprintf(stderr, "emalloc: Out of memory trying to allocate %zu bytes\n",
		size);
	fflush(stderr);
	abort();
}

void *emalloc(size_t size) {
	void *ptr = malloc(size);
	if (!ptr) emalloc_oom(size);
	increment_used_memory(size);
	return ptr;
}

void *erealloc(void *ptr, size_t size) {
	void *

